import pyglet
import pymunk as pm
from pymunk import Vec2d
import math
X,Y = 0,1
timeStep = 1.0 / 60
import random

def flipy(y):
    """Small hack to convert chipmunk physics to pygame coordinates"""
    return y+20

"""
def mouse_coll_func(s1, s2, cs, normal_coef, data):
    ""Simple callback that increases the radius of circles touching the mouse""
    if s2.collision_type != COLLTYPE_MOUSE and type(s2) == pm.Circle:
        s2.radius += 0.15
    return False
"""



### Physics stuff
pm.init_pymunk()
space = pm.Space()
space.gravity = Vec2d(0.0, -200.0)

### Static line
line_point1 = None
static_lines = []
run_physics = True

line_point1 = Vec2d(100, 80)
line_point2 = Vec2d(300, 450)

body = pm.Body(pm.inf, pm.inf)
shape= pm.Segment(body, line_point1, line_point2, 5)
shape.friction = 0.99
space.add_static(shape)
static_lines.append(shape)
line_point1 = None


 
window = pyglet.window.Window()
#sprite = pyglet.sprite.Sprite(image)
rain_img = pyglet.image.load('rain.png')
splash_img = pyglet.image.load('splash.png')
background_img = pyglet.image.load('background.png')
character_img = pyglet.image.load('character.png')
rain_img.anchor_x = rain_img.width // 2
rain_img.anchor_y = rain_img.height // 2
 
character_img.anchor_x = character_img.width // 2
character_img.anchor_y = character_img.height // 2

shapes = []

batch = pyglet.graphics.Batch()
sprites = []
elapsed_time = 0
rainval = 0
force = 0
windx = 0
movespeed = 250
drops_per_rainval_per_sec = 50
charpos = [150, 32]
movement = [0,0]
charsprite = pyglet.sprite.Sprite(character_img, batch=batch)

charbody = pm.Body(15, 10)
charbody.position = tuple(charpos)
charshape = pm.Circle(charbody, 32, Vec2d(0,0))
charshape.friction = .6
charshape.group = 1
space.add(charbody, charshape)

ground = pm.Body(0,0)
ground.position = (320,0)
line_point1 = Vec2d(-7000, -5)
line_point2 = Vec2d(7000, -5)
shape= pm.Segment(body, line_point1, line_point2, 5)
shape.friction = 0.9
space.add_static(shape)

def apply_impulse(shape, impulse_vector):
    """ Apply an Impulse to a given Shape
        Parameter: shape == pymunk.Shape(), impulse_vector == (int(x), int(y))
    """
    x, y = impulse_vector
    shape.body.apply_impulse(Vec2d(x, y), Vec2d(0,0))
    
def update(dt):
    global rainval, windx, movespeed
    ### Update physics
    #move our char around.
    #charshape.set_surface_velocity((movement[0]*movespeed*dt*1000,0))
    #charbody.apply_impulse((movement[0]*movespeed*dt*1000,0), Vec2d(0,0))
    #v = charbody.position
    #p = int(v.x), int(v.y)
    #charsprite.x = p[0]
    #charsprite.y = p[1]
    
    charpos[0] += movement[0] * movespeed * dt
    charsprite.x = charpos[0]
    charsprite.y = charpos[1]
    charbody.position = tuple(charpos)
    
    if run_physics:
        ### ADD falling items
        rainval = max(rainval, 0)
        #elapsed_time %= 1
        #drops = elapsed_time * drops_per_rainval_per_sec
        #print drops
        #elapsed_time %= (1/20.)
        for x in range(int(dt * drops_per_rainval_per_sec * rainval)):
            p = random.randrange(640), 490
            body = pm.Body(10, 100)
            body.position = p
            shape = pm.Circle(body, 10, Vec2d(0,0))
            shape.friction = 0.5
            shape.group = 100
            space.add(body, shape)
            shapes.append(shape)
            impulse_amt = windx * 10
            apply_impulse(shape, (impulse_amt,-900))
            sprites.append(pyglet.sprite.Sprite(rain_img, batch=batch))
            sprites[-1].opacity = 70
        
        #for x in range(int(phys_steps)):
        for x in range(1):
            #for y in shapes:
                
            space.step(dt)
            
from pyglet.window import key
@window.event
def on_key_press(symbol, modifiers):
    global rainval, windx, movement
    print 'A key was pressed', symbol
    if symbol == key.UP:
        rainval -= 1
    elif symbol == key.DOWN:
        rainval += 1
    elif symbol == key.LEFT:
        windx -= 50
    elif symbol == key.RIGHT:
        windx += 50
    elif symbol == key.A:
        movement[0] = -1
    elif symbol == key.D:
        movement[0] = 1
        
@window.event
def on_key_release(symbol, modifiers):
    global movement
    print 'A key was released', symbol
    if symbol == key.A:
        if movement[0] == -1:
            movement[0] = 0
    elif symbol == key.D:
        if movement[0] == 1:
            movement[0] = 0
        
@window.event
def on_draw():
    #print dir(window)
    white = (1,1,1,1)
    pyglet.gl.glClearColor(*white)
    window.clear()
    i = 0
    while i < len(shapes):
        ball = shapes[i]
        r = ball.radius
        v = ball.body.position
        p = int(v.x), int(v.y)
        #if p[1] > 600:
        #    screen.blit(splash, (p[0], 588))
        #print p[1]
        if p[1] < -10:
            space.remove(ball, ball.body) 
            shapes.pop(i)
            sprites[i].visible = False
            sprites.pop(i)
            
            continue
        rot = ball.body.velocity
        #pygame.draw.circle(screen, THECOLORS["blue"], p, int(r), 2)
        #pygame.draw.line(screen, THECOLORS["red"], p, p+p2)
        #temp = pygame.transform.rotate(img, -90+math.degrees(math.atan2(rot.x,rot.y)))
        sprites[i].x = p[0]
        sprites[i].y = p[1]
        sprites[i].rotation = 180+math.degrees(math.atan2(rot.x,rot.y))
        i += 1

    background_img.blit(0,0)
    batch.draw()
    #window.flip()
    
pyglet.clock.schedule_interval(update, timeStep)
pyglet.app.run()       
    
     